package com.boc.bus.control;

import java.beans.PropertyDescriptor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;

public class BusOutputResult {
	private static Map result = null;
	
	public BusOutputResult(){
		result = new HashMap();
	}
	
	public final void addValue(Object key,Object value){
		result.put(key, value==null?"":value);
	}
	
	/**
	 * 添加一个包含Map的结果集
	 * @param cursorName
	 * @param rows
	 */
	public final void addValue(Object cursorName,List<Map> rows){
		result.put(cursorName, rows);
	}
	/**
	 * 添加一个包含POJO的结果集
	 * @param cursorName
	 * @param rows 一个包含pojo的list对象
	 */
	public final void addValues(Object cursorName,List<?> result) throws NullPointerException {
		List<Map> list = new ArrayList();
		try {
			int rows = result.size();
			for (int index = 0 ; index < rows ; index ++) {
				list.add(transFormToMap(result.get(index)));
			}
			this.result.put(cursorName, list);
		} catch (NullPointerException e) {
			throw e;
		}
	}
	
	public final Map getResult(){
		return result;
	}
	
	/**
	 * 将一个POJO转换成一个Map
	 * @param bean
	 * @return
	 */
	public final static Map<String, Object> transFormToMap(Object bean) {
		Map<String, Object> params = new HashMap<String, Object>(0);
		try {
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(bean);
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (!StringUtils.equals(name,"class")) {
					Object value = propertyUtilsBean.getNestedProperty(bean, name);
					if(descriptors[i].getPropertyType().getName().equals("java.util.Date") && value != null) {
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						params.put(name, format.format(value));
					} else {
						params.put(name, value);
					}
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}
	
}
